package cn.chiship.framework.docs.biz.service.impl;

import cn.chiship.framework.common.constants.SystemConfigConstants;
import cn.chiship.framework.common.pojo.vo.ConfigJson;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.docs.biz.entity.FileCatalogConfigExample;
import cn.chiship.framework.docs.biz.entity.FileResources;
import cn.chiship.framework.docs.biz.entity.FileResourcesExample;
import cn.chiship.framework.docs.biz.mapper.FileResourcesMapper;
import cn.chiship.framework.docs.biz.pojo.dto.FileCatalogChangeStatusDto;
import cn.chiship.framework.docs.biz.pojo.dto.FileChangeStatusDto;
import cn.chiship.framework.docs.biz.service.FileChangeStatusService;
import cn.chiship.framework.docs.biz.service.FileResourcesService;
import cn.chiship.framework.docs.core.common.DocsCommonConstants;
import cn.chiship.framework.docs.core.common.FileCatalogChangeEnum;
import cn.chiship.framework.docs.core.common.FileChangeEnum;
import cn.chiship.framework.docs.core.properties.FileUploadProperties;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseCacheConstants;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.exception.custom.SystemErrorException;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.ObjectUtil;
import cn.chiship.sdk.core.util.RandomUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.docs.biz.entity.FileCatalogConfig;
import cn.chiship.framework.docs.biz.mapper.FileCatalogConfigMapper;
import cn.chiship.framework.docs.core.common.DocsCommonUtils;

import cn.chiship.sdk.framework.multipartFile.InputStreamToMultipartFile;
import cn.chiship.sdk.framework.pojo.vo.UploadVo;
import cn.chiship.sdk.third.core.model.DfsDTO;
import cn.chiship.sdk.third.storage.FileStorageService;
import cn.chiship.sdk.third.storage.enums.DfsEnum;
import cn.chiship.sdk.third.storage.factory.DfsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * FileResourcesService实现
 *
 * @author lijian
 * @date 2020/4/24
 */
@Service
public class FileResourcesServiceImpl extends BaseServiceImpl<FileResources, FileResourcesExample>
        implements FileResourcesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileResourcesServiceImpl.class);

    private static final int NUMBER_THREE = 3;

    @Resource
    FileResourcesMapper fileResourcesMapper;

    @Resource
    FileCatalogConfigMapper fileCatalogConfigMapper;

    @Resource
    private FileChangeStatusService fileChangeStatusService;

    @Resource
    private FileUploadProperties fileUploadProperties;

    @Resource
    private RedisService redisService;

    @Resource
    private GlobalCacheService globalCacheService;

    @Override
    public FileResources cacheByFileUuid(String fileUuid) {
        List<FileResources> fileResources = cacheByFileUuid(Arrays.asList(fileUuid));
        if (fileResources.isEmpty()) {
            return null;
        }
        return fileResources.get(0);
    }

    @Override
    public List<FileResources> cacheByFileUuid(List<String> fileUuid) {

        List<FileResources> files = new ArrayList<>();
        if (fileUuid.isEmpty()) {
            return files;
        }
        List<String> uuids = new ArrayList<>();
        for (String uuid : fileUuid) {
            if (uuid.startsWith("http://") || uuid.startsWith("https://")) {
                FileResources fileResources = new FileResources();
                fileResources.setFileUuid(uuid);
                fileResources.setOriginalFileName("网络图片");
                files.add(fileResources);
            } else {
                String key = CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_FILE_CONFIG_PREFIX) + ":" + uuid;
                if (redisService.hasKey(key)) {
                    files.add((FileResources) redisService.get(key));
                } else {
                    uuids.add(uuid);
                }
            }

        }
        if (!uuids.isEmpty()) {
            FileResourcesExample fileResourcesExample = new FileResourcesExample();
            FileResourcesExample.Criteria criteria = fileResourcesExample.createCriteria();
            criteria.andIsDeletedEqualTo(BaseConstants.NO).andFileUuidIn(uuids);
            List<FileResources> fileResources = fileResourcesMapper.selectByExample(fileResourcesExample);
            fileResources.forEach(file -> {
                files.add(file);
                String key = CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_FILE_CONFIG_PREFIX) + ":"
                        + file.getFileUuid();
                Long expireTime = 24L * 60 * 60;
                redisService.set(key, file, expireTime);
            });
        }
        return files;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult fileResourcesAdd(String catalogId, String fileName, String originalName, Long fileSize,
                                       String contentTyp, String fileExt, String userId, String userName, String realName, Byte storageLocation,
                                       String storagePath, String storageRelativePath) {
        FileResourcesExample fileResourcesExample = new FileResourcesExample();
        fileResourcesExample.createCriteria().andCatalogIdEqualTo(catalogId).andOriginalFileNameEqualTo(originalName);
        FileResources fileResources = new FileResources();
        fileResources.setId(SnowflakeIdUtil.generateStrId());
        fileResources.setIsDeleted(BaseConstants.NO);
        fileResources.setGmtCreated(System.currentTimeMillis());
        fileResources.setGmtModified(System.currentTimeMillis());
        fileResources.setFileUuid(RandomUtil.uuidLowerCase());
        fileResources.setFileName(fileName);
        fileResources.setIsBuiltIn(BaseConstants.NO);
        fileResources.setFileExt(fileExt);
        fileResources.setCatalogId(catalogId);
        fileResources.setOriginalFileName(originalName);
        fileResources.setFileSize(fileSize);
        fileResources.setFileContentType(contentTyp);
        fileResources.setFileType(DocsCommonUtils.getFileTypeByExt(fileExt));

        fileResources.setIsCollected(BaseConstants.NO);
        fileResources.setIsShared(BaseConstants.NO);
        fileResources.setIsEncryption(BaseConstants.NO);
        fileResources.setIsAllowDeleted(BaseConstants.NO);
        fileResources.setIsAllowRead(BaseConstants.YES);
        fileResources.setFileStatus("0:正常");
        fileResources.setFileComeSource("平台");

        fileResources.setUserId(userId);
        fileResources.setUserName(userName);
        fileResources.setRealName(realName);

        fileResources.setStorageLocation(storageLocation);
        fileResources.setStoragePath(storagePath);
        fileResources.setStorageRelativePath(storageRelativePath);
        BaseResult baseResult = insertSelective(fileResources);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        FileChangeStatusDto fileChangeStatusDto = new FileChangeStatusDto();
        fileChangeStatusDto.setOptionUserId(fileResources.getUserId());
        fileChangeStatusDto.setOptionUserName(fileResources.getUserName());
        fileChangeStatusDto.setOptionRealName(fileResources.getRealName());
        fileChangeStatusDto.setOriginalId(fileResources.getId());
        fileChangeStatusDto.setOriginalName(fileResources.getOriginalFileName());
        baseResult = fileChangeStatusService.saveChange(fileChangeStatusDto, FileChangeEnum.UPLOAD);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        baseResult.setData(fileResources);
        return baseResult;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult collectionAdd(String projectsId, String fileId, String userId, String userName, String realName) {
        LOGGER.info("进入收藏业务层");
        FileResources fileResources = fileResourcesMapper.selectByPrimaryKey(fileId);
        if (fileResources == null) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, "暂无此文件");
        }

        if (BaseConstants.YES == fileResources.getIsCollected()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, "此文件已被收藏,无需再次收藏");
        }
        fileResources.setIsCollected(BaseConstants.YES);
        fileResources.setGmtModified(System.currentTimeMillis());
        int i = fileResourcesMapper.updateByPrimaryKey(fileResources);
        if (i <= 0) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, null);
        }
        FileCatalogConfigExample fileCatalogConfigExample = new FileCatalogConfigExample();
        fileCatalogConfigExample.createCriteria().andCatalogTypeEqualTo(Byte.valueOf("1"))
                .andProjectsIdEqualTo(projectsId).andCatalogPathEqualTo("MyCollection");
        List<FileCatalogConfig> fileCatalogConfigs = fileCatalogConfigMapper.selectByExample(fileCatalogConfigExample);
        if (fileCatalogConfigs.isEmpty()) {
            return BaseResult.error(BaseResultEnum.FAILED, "缺少我的收藏文件夹");
        }

        FileResources targetFileResources = new FileResources();
        BeanUtils.copyProperties(fileResources, targetFileResources);
        targetFileResources.setGmtModified(System.currentTimeMillis());
        targetFileResources.setGmtCreated(System.currentTimeMillis());
        // 我的收藏
        targetFileResources.setCatalogId(fileCatalogConfigs.get(0).getId());
        targetFileResources.setUserId(userId);
        targetFileResources.setUserName(userName);
        targetFileResources.setRealName(realName);
        targetFileResources.setOriginalResourcesId(fileResources.getId());
        targetFileResources.setId(SnowflakeIdUtil.generateStrId());
        i = fileResourcesMapper.insertSelective(targetFileResources);
        if (i <= 0) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_INSERT, null);
        }

        FileChangeStatusDto fileChangeStatusDto = new FileChangeStatusDto();
        fileChangeStatusDto.setOptionUserId(userId);
        fileChangeStatusDto.setOptionUserName(userName);
        fileChangeStatusDto.setOptionRealName(realName);
        fileChangeStatusDto.setOriginalId(fileResources.getId());
        fileChangeStatusDto.setOriginalName(fileResources.getOriginalFileName() + "." + fileResources.getFileExt());
        BaseResult baseResult = fileChangeStatusService.saveChange(fileChangeStatusDto, FileChangeEnum.ADD_COLLECTION);
        LOGGER.info("结束收藏业务层");
        return baseResult;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult collectionCancel(String fileId, String userId, String userName, String realName) {

        FileResources fileResources = fileResourcesMapper.selectByPrimaryKey(fileId);
        if (fileResources == null) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, "暂无此文件");
        }
        if (fileResources.getOriginalResourcesId() == null) {
            if (BaseConstants.NO == fileResources.getIsCollected()) {
                return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, "此文件已被取消收藏,无需再次取消收藏");
            }
            fileResources.setIsCollected(BaseConstants.NO);
            fileResources.setGmtModified(System.currentTimeMillis());
            int i = fileResourcesMapper.updateByPrimaryKey(fileResources);
            if (i <= 0) {
                return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, null);
            }

            FileResourcesExample fileResourcesExample = new FileResourcesExample();
            fileResourcesExample.createCriteria().andOriginalResourcesIdEqualTo(fileId).andUserIdEqualTo(userId);
            fileResourcesMapper.deleteByExample(fileResourcesExample);
        } else {
            // 收藏入口
            fileResourcesMapper.deleteByPrimaryKey(fileId);
            FileResources originalResources = fileResourcesMapper
                    .selectByPrimaryKey(fileResources.getOriginalResourcesId());
            originalResources.setIsCollected(BaseConstants.NO);
            originalResources.setGmtModified(System.currentTimeMillis());
            int i = fileResourcesMapper.updateByPrimaryKey(originalResources);
            if (i <= 0) {
                return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, null);
            }
        }

        FileChangeStatusDto fileChangeStatusDto = new FileChangeStatusDto();
        fileChangeStatusDto.setOptionUserId(userId);
        fileChangeStatusDto.setOptionUserName(userName);
        fileChangeStatusDto.setOptionRealName(realName);
        fileChangeStatusDto.setOriginalId(fileResources.getId());
        fileChangeStatusDto.setOriginalName(fileResources.getOriginalFileName() + "." + fileResources.getFileExt());
        return fileChangeStatusService.saveChange(fileChangeStatusDto, FileChangeEnum.CANCEL_COLLECTION);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult moveToRecycleBin(String projectsId, String fileId, Byte type, String userId, String userName,
                                       String realName) {
        LOGGER.info("进入移入回收站业务层");

        FileResources fileResources = fileResourcesMapper.selectByPrimaryKey(fileId);
        if (fileResources == null) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, "暂无此文件");
        }
        fileResources.setGmtCreated(System.currentTimeMillis());
        fileResources.setGmtModified(System.currentTimeMillis());
        fileResources.setOriginalResourcesId(fileResources.getCatalogId());

        FileCatalogConfigExample fileCatalogConfigExample = new FileCatalogConfigExample();
        fileCatalogConfigExample.createCriteria().andCatalogTypeEqualTo(Byte.valueOf("5"))
                .andProjectsIdEqualTo(projectsId);
        List<FileCatalogConfig> fileCatalogConfigs = fileCatalogConfigMapper.selectByExample(fileCatalogConfigExample);
        if (fileCatalogConfigs.isEmpty()) {
            return BaseResult.error(BaseResultEnum.FAILED, "缺少回收站文件夹");
        }
        if (fileCatalogConfigs.size() != NUMBER_THREE) {
            return BaseResult.error(BaseResultEnum.FAILED, "回收站文件夹配置错误，不足三个");
        }

        for (FileCatalogConfig catalogConfig : fileCatalogConfigs) {
            // 个人
            if (Byte.valueOf("1").equals(type) && "PersonRecycleBin".equals(catalogConfig.getCatalogPath())) {
                fileResources.setCatalogId(catalogConfig.getId());
            }
            // 企业
            if (Byte.valueOf("0").equals(type) && "CompanyRecycleBin".equals(catalogConfig.getCatalogPath())) {
                fileResources.setCatalogId(catalogConfig.getId());
            }
        }
        int i = fileResourcesMapper.updateByPrimaryKey(fileResources);
        if (i <= 0) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, null);
        }
        FileChangeStatusDto fileChangeStatusDto = new FileChangeStatusDto();
        fileChangeStatusDto.setOptionUserId(userId);
        fileChangeStatusDto.setOptionUserName(userName);
        fileChangeStatusDto.setOptionRealName(realName);
        fileChangeStatusDto.setOriginalId(fileResources.getId());
        fileChangeStatusDto.setOriginalName(fileResources.getOriginalFileName() + "." + fileResources.getFileExt());
        BaseResult baseResult = fileChangeStatusService.saveChange(fileChangeStatusDto, FileChangeEnum.MOVE_RECYCLE);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        LOGGER.info("结束入移入回收站业务层");
        return baseResult;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult removeFile(String fileUuid) {
        String key = CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_FILE_CONFIG_PREFIX) + ":" + fileUuid;
        LOGGER.info("进入删除文件业务层");
        redisService.del(key);
        FileResourcesExample fileResourcesExample = new FileResourcesExample();
        fileResourcesExample.createCriteria().andFileUuidEqualTo(fileUuid);
        List<FileResources> fileResources = fileResourcesMapper.selectByExample(fileResourcesExample);
        if (fileResources.isEmpty()) {
            return BaseResult.ok();
        }
        FileResources file = fileResources.get(0);
        fileResourcesMapper.deleteByExample(fileResourcesExample);

        switch (file.getStorageLocation()) {
            case DocsCommonConstants.STORAGE_LOCATION_ALI_OSS:
            case DocsCommonConstants.STORAGE_LOCATION_TENCENT_OSS:

                FileStorageService fileStorageService = DfsFactory.getFileStorageService(
                        DfsEnum.getDfsEnum(Integer.valueOf(String.valueOf(fileUploadProperties.getStorageLocation()))),
                        getDfsDTO());
                BaseResult baseResult = fileStorageService.removeFile(file.getStorageRelativePath());
                if (!baseResult.isSuccess()) {
                    return baseResult;
                }
                break;
            default:
                if (Boolean.FALSE.equals(fileUploadProperties.removeFile(file.getStorageRelativePath()))) {
                    // 删除失败进入redis删除队列
                    redisService.hset(CommonCacheConstants.REDIS_REMOVE_FILE_UUID, fileUuid, file.getStorageRelativePath());
                }
        }
        LOGGER.info("结束删除文件业务层");
        return BaseResult.ok();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult reduction(String fileId, String userId, String userName, String realName) {
        FileResources fileResources = fileResourcesMapper.selectByPrimaryKey(fileId);
        if (StringUtil.isNull(fileResources)) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, "暂无此文件");
        }
        FileChangeStatusDto fileChangeStatusDto = new FileChangeStatusDto();
        fileChangeStatusDto.setOptionUserId(userId);
        fileChangeStatusDto.setOptionUserName(userName);
        fileChangeStatusDto.setOptionRealName(realName);
        fileChangeStatusDto.setOriginalId(fileResources.getId());
        fileChangeStatusDto.setOriginalName(fileResources.getOriginalFileName() + "." + fileResources.getFileExt());
        fileChangeStatusService.saveChange(fileChangeStatusDto, FileChangeEnum.REDUCTION_FILE);

        fileResources.setCatalogId(fileResources.getOriginalResourcesId());
        fileResources.setOriginalResourcesId(null);
        fileResources.setGmtModified(System.currentTimeMillis());
        fileResourcesMapper.updateByPrimaryKey(fileResources);
        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult rename(FileResources fileResources, String userId, String userName, String realName) {
        LOGGER.info("开始文件重命名业务层");

        fileResources.setGmtModified(System.currentTimeMillis());
        // 根据id获取文件信息
        FileResources fileResources2 = fileResourcesMapper.selectByPrimaryKey(fileResources.getId());

        FileResourcesExample fileResourcesExample = new FileResourcesExample();
        fileResourcesExample.createCriteria().andOriginalFileNameEqualTo(fileResources.getOriginalFileName())
                .andFileExtEqualTo(fileResources2.getFileExt()).andIdNotEqualTo(fileResources.getId())
                .andCatalogIdEqualTo(fileResources2.getCatalogId());
        List<FileResources> fileResourcesList = fileResourcesMapper.selectByExample(fileResourcesExample);
        if (!fileResourcesList.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "文件名称已存在，请重新输入");
        }
        BaseResult baseResult = updateByPrimaryKeySelective(fileResources);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }

        FileChangeStatusDto fileChangeStatusDto = new FileChangeStatusDto();
        fileChangeStatusDto.setOptionUserId(userId);
        fileChangeStatusDto.setOptionUserName(userName);
        fileChangeStatusDto.setOptionRealName(realName);
        fileChangeStatusDto.setOriginalId(fileResources.getId());
        fileChangeStatusDto.setOriginalName(fileResources2.getOriginalFileName() + "." + fileResources2.getFileExt());
        fileChangeStatusDto.setTargetId(fileResources.getId());
        fileChangeStatusDto.setTargetName(fileResources.getOriginalFileName() + "." + fileResources2.getFileExt());
        baseResult = fileChangeStatusService.saveChange(fileChangeStatusDto, FileChangeEnum.RENAME);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        LOGGER.info("结束文件重命名业务层");
        return baseResult;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult changeIsAllowDelete(Boolean isAllowDelete, String id, String userId, String userName,
                                          String realName) {
        // 根据id获取文件信息
        FileResources fileResources = fileResourcesMapper.selectByPrimaryKey(id);

        fileResources.setIsAllowDeleted(Boolean.TRUE.equals(isAllowDelete) ? BaseConstants.YES : BaseConstants.NO);
        int update = fileResourcesMapper.updateByPrimaryKeySelective(fileResources);
        if (update <= 0) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, "系统错误，更新失败");
        }

        FileCatalogChangeStatusDto fileCatalogChangeStatusDto = new FileCatalogChangeStatusDto();
        fileCatalogChangeStatusDto.setOptionUserId(userId);
        fileCatalogChangeStatusDto.setOptionUserName(userName);
        fileCatalogChangeStatusDto.setOptionRealName(realName);
        fileCatalogChangeStatusDto.setOriginalId(fileResources.getId());
        fileCatalogChangeStatusDto
                .setOriginalName(fileResources.getOriginalFileName() + "." + fileResources.getFileExt());
        return fileChangeStatusService.saveChange(fileCatalogChangeStatusDto,
                FileCatalogChangeEnum.CHANGE_IS_ALLOW_DELETE);
    }

    @Override
    public BaseResult deleteByExample(FileResourcesExample fileResourcesExample) {
        List<FileResources> fileResourcesList = fileResourcesMapper.selectByExample(fileResourcesExample);
        List<String> storageRelativePathList = fileResourcesList.stream().map(FileResources::getStorageRelativePath)
                .collect(Collectors.toList());

        fileResourcesMapper.deleteByExample(fileResourcesExample);

        /*
         * switch (file.getStorageLocation()) { case
         * DocsCommonConstants.STORAGE_LOCATION_ALI_OSS: case
         * DocsCommonConstants.STORAGE_LOCATION_TENCENT_OSS: case
         * DocsCommonConstants.STORAGE_LOCATION_BAIDU_OSS: FileStorageService
         * fileStorageService =
         * DfsFactory.getFileStorageService(DfsEnum.getDfsEnum(Integer.valueOf(String.
         * valueOf(fileUploadProperties.getStorageLocation())))); BaseResult baseResult =
         * fileStorageService.removeFile(file.getStorageRelativePath()); if
         * (!baseResult.isSuccess()) { return baseResult; } break; default: if
         * (!fileUploadProperties.removeFile(file.getStorageRelativePath())) {
         * //删除失败进入redis删除队列 redisService.hset(
         * CommonCacheConstants.REDIS_REMOVE_FILE_UUID, fileUuid,
         * file.getStorageRelativePath()); } }
         */
        return BaseResult.ok(null);

    }

    @Override
    public BaseResult uploadFile(InputStream inputStream, String catalogId, String fileName, String contentType,
                                 CacheUserVO cacheUserVO) throws IOException {
        MultipartFile multipartFile = InputStreamToMultipartFile.inputStreamConvert(fileName, contentType, inputStream);
        return uploadFile(multipartFile, catalogId, cacheUserVO);
    }

    @Override
    public BaseResult uploadFile(MultipartFile multipartFile, String catalogId, CacheUserVO cacheUserVO) {
        try {
            if (multipartFile.isEmpty()) {
                return BaseResult.error(BaseResultEnum.FAILED, "上传失败，请选择文件");
            }

            if (StringUtil.isNullOrEmpty(catalogId)) {
                return BaseResult.error("缺少参数[catalogId]");
            }
            if (StringUtil.isNullOrEmpty(fileUploadProperties.getFilePathByCatalogId(catalogId))) {
                return BaseResult.error("文件目录不存在,请核对");
            }
            /**
             * 文件相关属性
             */
            String originalName = multipartFile.getOriginalFilename();
            Long fileSize = multipartFile.getSize();
            String contentType = multipartFile.getContentType();
            String fileExt = originalName.substring(originalName.lastIndexOf(".") + 1);
            String fileName = RandomUtil.uuidLowerCase() + "." + fileExt;
            originalName = originalName.substring(0, originalName.lastIndexOf("."));

            /**
             * 相对路径
             */
            String fileRelativePath = fileUploadProperties
                    .getFileUrl(fileUploadProperties.getFilePathByCatalogId(catalogId));

            /**
             * 绝对路径
             */
            String fileAbsolutePath = fileUploadProperties
                    .getFileAbsolutePath(fileUploadProperties.getFilePathByCatalogId(catalogId));

            String storagePath = null;
            FileStorageService fileStorageService;

            switch (fileUploadProperties.getStorageLocation()) {
                case DocsCommonConstants.STORAGE_LOCATION_ALI_OSS:
                case DocsCommonConstants.STORAGE_LOCATION_TENCENT_OSS:
                    fileStorageService = DfsFactory.getFileStorageService(
                            DfsEnum.getDfsEnum(Integer.valueOf(String.valueOf(fileUploadProperties.getStorageLocation()))),
                            getDfsDTO());
                    BaseResult baseResult = fileStorageService.upload(multipartFile.getInputStream(), fileRelativePath,
                            fileName);
                    if (!baseResult.isSuccess()) {
                        return baseResult;
                    }
                    storagePath = baseResult.getData().toString();
                    break;
                default:
                    File tempPartFile = new File(fileAbsolutePath, fileName);
                    multipartFile.transferTo(tempPartFile);
            }
            String userId = null;
            String userName = null;
            String realName = null;
            if (ObjectUtil.isNotEmpty(cacheUserVO)) {
                userId = cacheUserVO.getId();
                userName = cacheUserVO.getUsername();
                realName = cacheUserVO.getRealName();
            }
            BaseResult baseResult = fileResourcesAdd(catalogId, fileName, originalName, fileSize, contentType, fileExt,
                    userId, userName, realName, fileUploadProperties.getStorageLocation(), storagePath,
                    fileRelativePath + "/" + fileName);
            if (!baseResult.isSuccess()) {
                return baseResult;
            }
            FileResources fileResources = (FileResources) baseResult.getData();
            UploadVo uploadVo = new UploadVo(fileResources.getId(), fileResources.getOriginalFileName(),
                    fileResources.getFileUuid(), fileResources.getFileSize(), fileResources.getFileType(),
                    fileResources.getFileExt(), fileResources.getStorageRelativePath(), fileResources.getRealName(),
                    fileResources.getGmtCreated());
            return BaseResult.ok(uploadVo);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error(new SystemErrorException(e));
        }
    }

    private DfsDTO getDfsDTO() {
        /*
         * ACCESS_KEY storageAccessKey SECRET_KEY storageSecretKey 空间域名 storageEndPort
         * 存储空间名称 storageBuckName 存储根名称 storageRoot
         */
        ConfigJson configJson = globalCacheService
                .getSystemConfigJson(Arrays.asList(SystemConfigConstants.STORAGE_ACCESS_KEY,
                        SystemConfigConstants.STORAGE_SECRET_KEY, SystemConfigConstants.STORAGE_END_PORT,
                        SystemConfigConstants.STORAGE_BUCK_NAME, SystemConfigConstants.STORAGE_ROOT));
        DfsDTO dfsDTO = new DfsDTO();
        dfsDTO.setAppKey(configJson.getString(SystemConfigConstants.STORAGE_ACCESS_KEY));
        dfsDTO.setAppSecret(configJson.getString(SystemConfigConstants.STORAGE_SECRET_KEY));
        dfsDTO.setEndPort(configJson.getString(SystemConfigConstants.STORAGE_END_PORT));
        dfsDTO.setBuckName(configJson.getString(SystemConfigConstants.STORAGE_BUCK_NAME));
        dfsDTO.setRoot(configJson.getString(SystemConfigConstants.STORAGE_ROOT));
        return dfsDTO;
    }

    @Override
    public BaseResult listSameFolderFileByUuid(String uuid) {
        FileResourcesExample fileResourcesExample = new FileResourcesExample();
        fileResourcesExample.createCriteria().andFileUuidEqualTo(uuid);
        List<FileResources> fileResources = fileResourcesMapper.selectByExample(fileResourcesExample);
        if (fileResources.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, "暂无文件信息");
        }
        fileResourcesExample = new FileResourcesExample();
        fileResourcesExample.createCriteria().andCatalogIdEqualTo(fileResources.get(0).getCatalogId())
                .andFileTypeEqualTo(fileResources.get(0).getFileType());
        return BaseResult.ok(fileResourcesMapper.selectByExample(fileResourcesExample));
    }

}
